package gl.java.umsp.match;

import gl.java.umsp.ErrCode;
import gl.java.umsp.bean.Match;
import gl.java.umsp.bean.MatchResult;
import gl.java.umsp.bean.Room;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 快速随机匹配,人满一次后直到房间释放前不允许其他人再次加入.<br>
 *
 * @author geliang
 */
@Slf4j
public class QuickMatch implements IMatch {
    WaitingRoomList roomList;

    public QuickMatch() {
        roomList = new WaitingRoomList();
        MatchUserEventDispatcher.getInstance().add(roomList);
    }

    @Override
    public void match(Match match, IMatchedCallBack listener) {
        Room idleRoom = roomList.findRoom(match, new IRoomMatchFilter() {
            @Override
            public Room filter(List<Room> list, Match match) {
                for (Room room : list) {
                    if (!room.isFullUser()) {
                        log.info("find room is not enough user,roomID"+room.roomID);
                        return room;
                    }
                }
                return null;
            }
        });
        if (idleRoom == null) {
            listener.onMatched(MatchResult.createFailMatchResult(ErrCode.RoomNotEnough,match.getWantToMatchUser().userID));
        } else {
            idleRoom.putUserIntoBeMatchList(match.getWantToMatchUser());
            listener.onMatched(MatchResult.createSuccessMatchResult(match, idleRoom));
        }
    }

    @Override
    public int getMatchType() {
        return MatchType.RANDOM;
    }

}
